package com.copro.chemdb.stat.rule.export;

import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.ihelpuoo.util.Properties;

import com.copro.chemdb.stat.ExportRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;

public class Rule4 implements ExportRule {

	@SuppressWarnings("unchecked")
	@Override
	public void doExport(HSSFWorkbook wb, Subject subject, StatResult re,
			short customStyle, Application app) throws SimpleException {
		Map<String, Object> result = (Map<String, Object>) re.getResult();
		String text = (String) result.get("text");
		if (text.length() > 30) {
			text = text.substring(0, 30);
		}
		// create new sheet
		HSSFSheet sheet = wb.createSheet(text);
		// set the header
		HSSFRow row = sheet.createRow(0);
		String[] titles = (String[]) result.get("title");
		for (int i = 0; i < titles.length; i++) {
			CellUtil.createCell(row, i, titles[i], wb
					.getCellStyleAt((short) (customStyle + StyleHeader)));
		}
		// set the data body
		List<List<String>> rows = (List<List<String>>) result.get("rows");
		for (int i = 0; i < rows.size(); i++) {
			List<String> cells = rows.get(i);
			row = sheet.createRow(i + 1);
			CellUtil.createCell(row, 0, cells.get(0));
			for (int j = 1; j < cells.size(); j++) {
				CellUtil
						.createCell(
								row,
								j,
								Double.parseDouble(cells.get(j)),
								wb
										.getCellStyleAt((short) (customStyle + StylePercent)));
			}
		}

		// set the footer body
		List<String> total = (List<String>) result.get("total");
		row = sheet.createRow(rows.size() + 1);
		CellUtil.createCell(row, 0, "平均", wb
				.getCellStyleAt((short) (customStyle + StyleHeader)));
		for (int j = 0; j < total.size(); j++) {
			CellUtil
					.createCell(
							row,
							j + 1,
							Double.parseDouble(total.get(j)),
							wb
									.getCellStyleAt((short) (customStyle + StyleHeaderPercent)));
		}
	}

	@Override
	public void setup(Properties conf) {
	}

}
